import logging


from app.models.article import Category

"""
获取文章分类列表
"""
def get_category_list_by_user_id(user_id):
    try:
        categories = Category.query.filter_by(user_id=user_id).all()
        return[category.to_dict() for category in categories]
    except Exception as e:
        logging.error(e)
        return None

"""
添加分类
"""
def create_category_by_user(data):
    try:
        # 检查分类是否已存在
        existing_category = Category.query.filter_by(
            name=data['name'], 
            user_id=data['user_id']
        ).first()
        if existing_category:
            logging.error(f"分类已存在: {data['name']}")
            return None
            
        # 创建新分类
        category = Category(
            name=data['name'],
            user_id=data['user_id']
        )
        category.save()
        return category
    except Exception as e:
        logging.error(f"添加分类失败: {str(e)}")
        return None

"""
编辑文章分类
"""
def update_category_by_id(data):
    try:
        category = Category.query.get(data['id'])
        if category:
            category.name = data['name']
            category.save()
            return category
        else:
            return None
    except Exception as e:
        logging.error(f"修改分类失败:{str(e)}")
        return None

"""
删除文章分类
"""
def delete_category_by_id(category_id):
    try:
        category = Category.query.get(category_id)
        if category:
            category.delete()
            return True
        else:
            return False
    except Exception as e:
        logging.error(f"删除分类失败:{str(e)}")
        return False
